<script setup lang="ts">
import { onBeforeMount, ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useTradingAccountStore } from '@/stores/stock'
import { ListStock, CreateStock, UpdateStock, CreatePlan } from '@/api/note'
import { Delete, Search, Plus } from '@element-plus/icons-vue'

const router = useRouter()
const store = useTradingAccountStore()

const dialog = reactive({
  stock: false,
  plan: false,
  updateStock: false,
})

const searchKey = ref('')

const searchStock = function () {
  reqStock(1)
}

const stockAddForm = ref({
  code: '',
})

const stockUpdateForm = ref({
  id: 0,
  name: '',
})

const AddStock = function () {
  CreateStock(store.currentTradingAccount.id, stockAddForm.value.code).then((resp) => {
    if (resp.code === 0) {
      ElMessage.success(resp.msg)
      dialog.stock = false
      reqStock(1)
      stockAddForm.value.code = ''
    }
  })
}

const EditStock = function () {
  UpdateStock(
    store.currentTradingAccount.id,
    stockUpdateForm.value.id,
    stockUpdateForm.value.name,
  ).then((resp) => {
    if (resp.code === 0) {
      ElMessage.success(resp.msg)
      dialog.updateStock = false
      reqStock(1)
      stockUpdateForm.value.name = ''
    }
  })
}

// 页面初始化
onBeforeMount(() => {
  if (store.currentTradingAccount.id) {
    init()
  }
})

watch(
  () => store.currentTradingAccount,
  () => {
    init()
  },
)

const init = function () {
  reqStock(1)
}

// Stock
const stockPageData = ref({
  total: 0,
  pageSize: 10,
  list: [],
})

const reqStock = function (num) {
  let key = searchKey.value

  ListStock(store.currentTradingAccount.id, key, num, 10).then((resp) => {
    if (resp.code === 0) {
      stockPageData.value = resp.data
    }
  })
}

// Plan
const emptyPlanForm = {
  StockId: 0,
  TakeProfitPrice: 0,
  StopLossPrice: 0,
  ValuationAnalysis: [{ value: '' }],
}
const planAddForm = reactive(JSON.parse(JSON.stringify(emptyPlanForm)))

const AddPlan = function () {
  let reasons = []
  for (let i = 0; i < planAddForm.ValuationAnalysis.length; i++) {
    reasons.push(planAddForm.ValuationAnalysis[i].value)
  }
  CreatePlan(
    store.currentTradingAccount.id,
    planAddForm.StockId,
    planAddForm.title,
    planAddForm.TakeProfitPrice,
    planAddForm.StopLossPrice,
    reasons,
  ).then((resp) => {
    if (resp.code === 0) {
      ElMessage.success(resp.msg)
      dialog.plan = false
      init()
    }
  })
}
</script>

<template>
  <div>
    <!--  表格展示     -->
    <div class="stock">
      <el-table :data="stockPageData.list" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="code" label="Code" width="180" />
        <el-table-column prop="name" label="Name" width="180" />
        <el-table-column prop="planStatus" label="PlanStatus" width="180">
          <template #default="scope">
            <el-tag size="small" type="success" v-if="scope.row.planStatus == 0">进行中</el-tag>
            <el-tag size="small" type="danger" v-else-if="scope.row.planStatus == 1">已完结</el-tag>
            <el-tag size="small" type="info" v-else>不存在</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="Operations" min-width="120">
          <template #header>
            <el-text type="warning" @click="dialog.stock = true" style="cursor: pointer">
              添加 Stock
            </el-text>
            <el-input
              v-model="searchKey"
              style="margin-left: 10px; width: 160px"
              @change="searchStock"
              :prefix-icon="Search"
              placeholder="search stock"
            />
          </template>
          <!-- 操作-->
          <template #default="scope">
            <el-button link type="primary" size="small"> 统计 </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="
                dialog.updateStock = true;
                stockUpdateForm.id = scope.row.id;
                stockUpdateForm.name = scope.row.name;
              "
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              v-if="scope.row.planStatus != -1"
              @click="router.push('/note/stock/plan/list?stockId=' + scope.row.id)"
            >
              历史计划
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="
                router.push(
                  '/note/stock/operate?stockId=' + scope.row.id + '&planId=' + scope.row.planId,
                )
              "
              v-if="scope.row.planStatus === 0"
            >
              记录
            </el-button>
            <el-button
              v-else
              link
              type="primary"
              size="small"
              @click="
                dialog.plan = true;
                planAddForm.StockId = scope.row.id;
              "
            >
              添加计划
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @update:current-page="reqStock"
        :page-size="stockPageData.pageSize"
        layout="prev, pager, next"
        :total="stockPageData.total"
        size="large"
      />
    </div>

    <!--    添加Stock弹框   -->
    <el-dialog v-model="dialog.stock" title="添加标的" width="300">
      <el-form :model="stockAddForm">
        <el-form-item label="Code" label-width="60px">
          <el-input v-model="stockAddForm.code" style="width: 150px" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="AddStock">确认</el-button>
      </template>
    </el-dialog>

    <!--    更新Stock弹框   -->
    <el-dialog v-model="dialog.updateStock" title="修改名称" width="300">
      <el-form :model="stockUpdateForm">
        <el-form-item label="名称" label-width="60px">
          <el-input v-model="stockUpdateForm.name" style="width: 150px" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="EditStock">确认</el-button>
      </template>
    </el-dialog>

    <!--    添加Plan弹框   -->
    <el-dialog
      v-model="dialog.plan"
      @closed="planAddForm = reactive(JSON.parse(JSON.stringify(emptyPlanForm)))"
      title="添加交易计划"
      width="700"
    >
      <el-form :model="planAddForm">
        <el-form-item label="交易标题" label-width="100px">
          <el-input style="width: 330px" v-model="planAddForm.title" autocomplete="off" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="止盈价格" label-width="100px">
              <el-input
                v-model.number="planAddForm.TakeProfitPrice"
                type="number"
                style="width: 100px"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :inline="true" label="止损价格" label-width="100px">
              <el-input
                v-model.number="planAddForm.StopLossPrice"
                type="number"
                style="width: 100px"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="价值分析" label-width="100px">
          <el-col>
            <el-row
              v-for="(item, index) in planAddForm.ValuationAnalysis"
              :key="index"
              style="margin-bottom: 20px"
            >
              <el-input
                v-model="item.value"
                style="width: 400px"
                placeholder="请输入内容"
                type="textarea"
                rows="1"
              />
              <el-button
                circle
                @click="planAddForm.ValuationAnalysis.splice(index, 1)"
                style="margin-left: 10px"
              >
                <el-icon> <Delete /> </el-icon>
              </el-button>

              <el-button circle @click="planAddForm.ValuationAnalysis.push({ value: '' })">
                <el-icon> <Plus /> </el-icon>
              </el-button>
            </el-row>
          </el-col>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="AddPlan">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped></style>
